using UnityEngine;
using UnityEngine.Networking;

namespace PKGames.AssetBundleSystem
{
	public class CachedAssetBundleLoader : AssetBundleLoader
	{
		private string _url = string.Empty;

		private UnityWebRequest _downloadRequest;

		private Hash128 _assetBundleHash;

		public CachedAssetBundleLoader(string assetBundleName, Hash128 assetBundleHash, string url)
		{
			_assetBundleName = assetBundleName;
			_url = url;
			_assetBundleHash = assetBundleHash;
			_assetBundle = AssetBundleCache.GetCachedAssetBundle(_assetBundleName);
		}

		public override void Start()
		{
			if (_assetBundle == null)
			{
				string uri = _url + _assetBundleName;
				_downloadRequest = UnityWebRequestAssetBundle.GetAssetBundle(uri, _assetBundleHash);
				_downloadRequest.SendWebRequest();
			}
		}

		public override bool IsDone()
		{
			return _downloadRequest == null || _downloadRequest.isDone;
		}

		public override float GetProgress()
		{
			if (_downloadRequest != null)
			{
				return _downloadRequest.downloadProgress;
			}
			return 1f;
		}

		public override string GetError()
		{
			if (_downloadRequest == null)
			{
				return string.Empty;
			}
			return _downloadRequest.error;
		}

		public override AssetBundle GetAssetBundle()
		{
			if (_assetBundle == null && IsDone() && string.IsNullOrEmpty(GetError()))
			{
				DownloadHandlerAssetBundle downloadHandlerAssetBundle = _downloadRequest.downloadHandler as DownloadHandlerAssetBundle;
				if (downloadHandlerAssetBundle != null)
				{
					_assetBundle = downloadHandlerAssetBundle.assetBundle;
					AddAssetBundleToCache(_assetBundleName, _assetBundle);
				}
			}
			return _assetBundle;
		}

		public override void Cleanup()
		{
			if (_downloadRequest != null)
			{
				_downloadRequest.Dispose();
				_downloadRequest = null;
			}
		}
	}
}
